﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using Microsoft.Win32;

namespace Scripni.SourceControlSelector.Core
{
	public class Configuration
	{
		public List<SourceControlProvider> ConfiguredProviders = new List<SourceControlProvider>
			{
				new SourceControlProvider(
					Guid.Parse("4CA58AB2-18FA-4F8D-95D4-32DDF27D184C"), "Visual Studio Team Foundation Server"),
				new SourceControlProvider(Guid.Parse("53544C4D-FFD5-48A9-B04A-0700CCD31070"), "Microsoft MSSCCI Support Provider"),
				new SourceControlProvider(
					Guid.Parse("8770915B-B235-42EC-BBC6-8E93286E59B5"), "AnkhSVN - Subversion Support for Visual Studio"),
				new SourceControlProvider(Guid.Parse("dadada00-63c7-4363-b107-ad5d9d915d45"), "VisualHG")
			};

		public SourceControlProvider GetProvider(string path)
		{
			DirectoryInfo inf = new DirectoryInfo(path);

			while (inf.Parent != null)
			{
				if (inf.GetDirectories(".hg", SearchOption.TopDirectoryOnly).Any())
				{
					return ConfiguredProviders[3];
				}
				if (inf.GetDirectories(".svn", SearchOption.TopDirectoryOnly).Any())
				{
					return ConfiguredProviders[2];
				}
				inf = inf.Parent;
			}

			return null;
		}

		public void SetCurrentProvider(SourceControlProvider provider)
		{
			RegistryKey currentSccKey =
				Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\VisualStudio\11.0\CurrentSourceControlProvider", true);
			currentSccKey.SetValue(string.Empty, "{" + provider.Key.ToString() + "}");
		}


	}

	public class SourceControlProvider
	{
		public SourceControlProvider(Guid key, string name)
		{
			this.key = key;
			this.name = name;
		}

		public string Name
		{
			get
			{
				return this.name;
			}
		}

		private readonly Guid key;

		private readonly string name;
		public Guid Key
		{
			get
			{
				return this.key;
			}
		}
	}
}
